import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {ActivityService} from "../activity.service";
import {Observable} from "rxjs/Observable";
import {EditorComponent} from "../../../comm-components/wangeditor/editor.component";
import {AdOssUploadService} from "../../../lib/service/ad-oss-upload.service";
import {GroupService} from "../../group/group.service";
import {NzMessageService} from "ng-zorro-antd";
import {LocalStorageService} from "../../../lib/service/local-storage.service";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {AliyunOssOutputUrl} from "../../../../config/api";
import {DisplayService} from "../../display/display.service";

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.scss'],
  providers: [ActivityService, GroupService]
})
export class EditComponent implements OnInit {

  id;
  type = 0;
  stage = 2;
  status1 = 1;

  activityName = '活动';
  validateForm:FormGroup;
  loading = false;
  page = 1;
  pageSize = 5;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  _isSpinning = false;
  isConfirmLoading = false;
  description;
  cacheCurrentIds = [];
  cacheCurrentActivityIds = [];
  fileList = [];
  picList = [];
  f1 = ['activityCover'];
  picSizeInfo;
  submitStatus = false;
  recoverGoodsIds = [];

  //商品弹窗
  goodsModalVisible = false;
  selectedGroup;
  keyword = '';
  status = '上架';
  total = 0;
  goodsList = [];
  groupList = [];
  hasCheckedSku = true;
  currentClickGoods = [];
  checkedGoodsInfo = [];
  currentGoodsPrice = 0;
  comparePriceStatus = false;
  skuStatus = false;
  highPriceSkuId = null;
  ghostData = null;
  randomStatus = false;
  activity_goods_prize = [];
  activity_goods_ids = [];
  ImageChange = false;
  ImageChangeNum = 0;


  //活动弹窗
  activityModalVisible = false;
  activityList = [];
  activityLoading = false;
  activitiesTotal;
  currentClickActivity = [];
  checkedActivityInfo = [];
  activity_ids = [];
  activityClickIndex;
  self = this;
  isConfirmActivityLoading = false;

  typeText = {
    1: { text: '普通拼团', color: 'rgb(299,112,23)' },
    2: { text: '拉新拼团', color: 'rgb(299,112,23)' },
    3: { text: '抽奖拼团', color: 'rgb(299,112,23)' },
    4: { text: '团长免单', color: 'rgb(299,112,23)' },
  };
  num = 0;


  @ViewChild(EditorComponent) editor: EditorComponent;

  constructor(
    private fb: FormBuilder,
    private activityService: ActivityService,
    private groupService: GroupService,
    private displayService: DisplayService,
    private _message: NzMessageService,
    private router: Router,
    private adOssUploadService: AdOssUploadService,
    private localStorageService: LocalStorageService,
    private route: ActivatedRoute
  ) {
    this.validateForm = fb.group({
      id: ['', [Validators.required]],
      title: ['', [Validators.required, Validators.maxLength(30)]],
    });
  }

  ngOnInit() {
    this.id = +this.route.snapshot.params['id'];
    this.editor.changedEitorUsePlace('activity');
    if(this.id) {
      this.getActivityInfo(this.id);
    }
    this.getGroupList();

  }

  keyDown(e,which) {
    switch (e.code + which) {
      case 'Enter1':
        this.searchGoods();
        break;
      case 'Enter2':
        this.searchActivity();
        break;
    }
  }

//返回control
  getFormControl(name) {
    return this.validateForm.controls[name];
  }

    uploadImg(activity_plan_id) {
        this.adOssUploadService
            .getSignature('/v1/common/activity_plan/cover/' + activity_plan_id + '?callback=true')
            .subscribe(
                res1 => {
                    let length = this.fileList.filter(item => {
                        return item && item != "pic";
                    }).length;
                    let successLen = 0;
                    if (length == 0 && this.ImageChange) {
                        this.submitStatus = false;
                        this._message.create("success", '修改成功');
                        return false;
                    }
                    this.fileList.every((val, idx, array) => {
                        if (val && val != "pic") {
                            this.adOssUploadService.fileUpload(val, res1.data, this.f1[idx] + '.' + val.name.replace(/.+\./, '').toLowerCase(), 'image')
                                .subscribe(res2 => {
                                        successLen++;
                                        if (successLen == length) {
                                            this.submitStatus = false;
                                            this._message.create('success', '修改成功');
                                            this.router.navigate(['member/activity/list']);
                                        }
                                    }
                                );
                        }
                        return true;
                    });

                }
            );
    }


  getActivityInfo(id) {
    this._isSpinning = true;
    this.activityService.getActivityInfo(id).subscribe(res => {
      if(res.code === 2000) {
        // console.log(res.data.activity_list);
        res.data.activity_list.map((e,i) => {
          e['type'] = this.typeText[e['activity_goods'][0]['type']];
          this.displayService.getActivityGoodsList(e.id, e['activity_goods'][0]['id']).subscribe(res => {
            if (res.code === 2000) {
              e['goodsDetail'] = res.data;
            }
          });
        });
        this.picList.push({ src: `${AliyunOssOutputUrl}/${res.data.cover_url}?update=${Date.now()}` });
        // this.checkedActivityInfo = this.activity_ids = res.data.activity_list;
        // this.checkedGoodsInfo = this.activity_goods_ids = res.data.goods;
        this.checkedActivityInfo = res.data.activity_list;
        this.activity_ids = JSON.parse(JSON.stringify(this.checkedActivityInfo));
        this.checkedGoodsInfo = res.data.goods;
        this.activity_goods_ids = JSON.parse(JSON.stringify(this.checkedGoodsInfo));
        this.validateForm.controls['title'].setValue(res.data.title);
        this.editor.loadingHandle(res.data.description);
        this.validateForm.controls['id'].setValue(res.data.id);
        this._isSpinning = false;
      }
    })
  }


  picError = false; //图片是否错误
  fileChange() {
    this.ImageChangeNum++;
    if (this.fileList.length == 0 && this.picList.length == 0) {
      this.picError = true;
    } else {
      this.picError = false;
    }
    if(this.ImageChangeNum > 1) {
        this.ImageChange = true;
    }
  }


  PostData(event): void {
    // console.log(event);
  }

  //价格验证
  priceValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if(control.value > this.currentGoodsPrice) {
        observer.next({ error:true, priceToHigh: true} );
      } else {
        observer.next(null);
      }
      observer.complete();
    })
  };

  // 添加商品
  addGoods() {
    // this.currentClickGoods = this.activity_goods_ids;
    this.currentClickGoods = this.checkedGoodsInfo;
    this.cacheCurrentIds = [];
    // this.checkedGoodsInfo.forEach((e) => {
    //   this.cacheCurrentIds.push(e.id);
    // });
    this.goodsModalVisible = true;
    this.page = 1;
    this.getGoodsList();
  }

  // 关闭添加商品弹窗
  closeModal() {
    this.currentClickGoods = this.checkedGoodsInfo;
    this.cacheCurrentIds.map((e,i) => {
      this.goodsList.map((e1,i1) => {
        if(e == e1.id) {
          e1['checked'] = false;
        }
      });
      this.activity_goods_ids.map((e2,i2) => {
        if(e == e2.id) {
          this.activity_goods_ids.splice(i2,1);
        }
      });
    });


    this.recoverGoodsIds.map((e,i) => {
      this.activity_goods_ids.push(e);
    });

    this.goodsModalVisible = false;

  }
  // 确认选择商品
  confirmCheckedGoods() {

    // this.recoverGoodsIds.map((e,i) => {
    //   this.activity_goods_ids.push(e);
    // });

    if(this.activity_goods_ids.length === 0) {
      this._message.create('error', '请选择商品');
      this.isConfirmLoading = false;
      return;
    }
    this.isConfirmLoading = true;
    this.skuStatus = true;
    // this.checkedGoodsInfo = JSON.parse(JSON.stringify(this.activity_goods_ids));
    this.checkedGoodsInfo = this.currentClickGoods;
    // this.recoverGoodsIds = [];
    // 获取选择商品的sku
    this.checkedGoodsInfo.map((e,i) => {
      this.groupService.getGoodsSkuList(e['id'],100).subscribe(res => {
        if (res.code === 2000) {
          const sku = res.data.data;
          const activity_goods_prize = [];
          sku.map((val, idx) => {
            val.checked = true;
            const sku_item = {'sku_id': val.id, 'number': val.in_stock};
            activity_goods_prize.push(sku_item);
          });
          e['activity_goods_prize'] = activity_goods_prize;
          e['sku'] = sku;
          e['hasCheckedSku'] = false;
          this.isConfirmLoading = false;
          this.goodsModalVisible = false;
        } else {
          this._message.create('error', res.message);
        }
      });

    });
  }

  searchGoods() {
    this.page = 1;
    this.getGoodsList();
  }

  // 处理商品的sku
  dealSku() {
    this.checkedGoodsInfo.map((e,i) => {
      const activity_goods_prize = [];
      if(!!e['sku'].length) {
        e['sku'].every((val, idx, array) => {
          if (val.checked) {
            const sku_item = {'sku_id': val.id, 'number': val.in_stock};
            activity_goods_prize.push(sku_item);
          }
          return true;
        });
        e['activity_goods_prize'] = activity_goods_prize;
        if (!e['activity_goods_prize'].length) {
          e['hasCheckedSku'] = false;
        }
      };
    });
  }

  // 获取商品列表
  getGoodsList() {
    this.loading = true;
    return new Promise((resolve, reject) => {
      this.groupService.getGoodsList(this.page, this.pageSize, this.selectedGroup, this.keyword, this.status).subscribe(res => {
        if (res.code === 2000) {
          this.total = res.data.total;
          const goodsList = res.data.data;
          const goodsId = [];
          goodsList.forEach(item => {
            goodsId.push(item.id);
            item['checked'] = false;
            this.checkedGoodsInfo.forEach((item1) => {
              if(item1.id == item.id) {
                item['checked'] = true;
              }
            });
            this.cacheCurrentIds.forEach((item2) => {
              if(item2 == item.id) {
                item['checked'] = true;
              }
            });
          });
          this.groupService.getbindListAll('[' + goodsId.join(',') + ']').subscribe(rs => {
            if (rs.code === 2000) {
              const goodsjson = {};
              rs.data.forEach(item => {
                if (!goodsjson[item.goods_id]) {
                  goodsjson[item.goods_id] = [item.name];
                } else {
                  goodsjson[item.goods_id].push(item.name);
                }
              });
              goodsList.forEach(item => {
                if (item.goods_number) {
                  item.goods_number=item.goods_number.split('|');
                }
                item.goods_category = goodsjson[item.id];
              });
            }
            this.goodsList = goodsList;
            this.loading = false;
            resolve();
          });
        } else {
          this._message.create('error', res.message);
        }
        this.loading = false;
      });
    })
  }



  //活动逻辑
  getActivityList() {
    this.activityLoading = true;
    this.displayService.getActivityList(this.page, this.pageSize, this.keyword ,this.type, this.stage, this.status1).subscribe(res => {
      if (res.code === 2000) {
        this.activityList = res.data.data;
        this.activityList.map((e, i) => {
          e['flexable'] = false;
          e['checked'] = false;
          this.checkedActivityInfo.map((e1,i1) => {
            if(e1.id == e.id) {
              e['checked'] = true;
            }
          });
          this.cacheCurrentActivityIds.forEach((item2) => {
            if(item2 == e.id) {
              e['checked'] = true;
            }
          })
        });
        this.activitiesTotal = res.data.total;
        this.activityLoading = false;
      }
    })
  }

  // 获取店铺商品类型列表
  getGroupList() {
    this.groupService.getGroupList().subscribe(res => {
      this.groupList = res.data.data;
    });
  }

  resetActivity() {
    this.keyword = '';
    this.page = 1;
    this.getActivityList();
  }

  resetGoods() {
    this.keyword = '';
    this.selectedGroup = null;
    this.page = 1;
    this.getGoodsList();
  }

  deleteGoods(i) {
    this.checkedGoodsInfo.splice(i,1);
    this.activity_goods_ids = this.checkedGoodsInfo;
  }
  deleteActivity(i) {
    this.checkedActivityInfo.splice(i,1);
    this.activity_ids = this.checkedActivityInfo;
  }

  searchActivity() {
    this.page = 1;
    this.getActivityList();
  }
  //打开活动模态框

  addActivity() {
    this.keyword = '';
    this.page = 1;
    this.pageSize = 5;
    this.currentClickActivity = this.activity_ids;
    this.cacheCurrentActivityIds = [];
    this.activityModalVisible = true;
    this.getActivityList();
  }
  //关闭活动模态框
  closeActivityModal() {
    this.currentClickActivity = this.checkedActivityInfo;
    this.activityList.map((e, i) => {
      e['flexable'] = false;
    });

    this.cacheCurrentActivityIds.map((e,i) => {
      this.activityList.map((e1,i1) => {
        if(e == e1.id) {
          e1['checked'] = false;
        }
      });
      this.activity_ids.map((e2,i2) => {
        if(e == e2.id) {
          this.activity_ids.splice(i2,1);
        }
      });
    });
    this.activityModalVisible = false;
  }
  //确认活动模态框
  confirmCheckedActivity() {
    if(this.currentClickActivity.length === 0) {
      this._message.create('error', '请选择活动');
      this.isConfirmActivityLoading = false;
      return;
    }
    // this.checkedActivityInfo = [];
    // this.isConfirmActivityLoading = true;
    // this.activityList.map((e,i) => {
    //   this.currentClickActivity.map((e1,i1) => {
    //     if(e.id == e1.id) {
    //       this.checkedActivityInfo.push(e1);
    //       let targetIndex = this.checkedActivityInfo.length - 1;
    //       this.checkedActivityInfo[targetIndex]['flexable'] =false;
    //       this.checkedActivityInfo[targetIndex]['type'] = this.typeText[e1['activity_goods'][0]['type']];
    //       this.displayService.getActivityGoodsList(e1['id'], e1['activity_goods'][0]['id']).subscribe(res => {
    //         if (res.code === 2000) {
    //           this.checkedActivityInfo[targetIndex]['goodsDetail'] = res.data;
    //         }
    //       });
    //     }
    //   });
    // });
    this.checkedActivityInfo = this.currentClickActivity;
    this.isConfirmActivityLoading = true;
    this.checkedActivityInfo.map((e, i) => {
      e['flexable'] = false;
      this.currentClickActivity.map((e1, i1) => {
        if (e == e1) {
          e['type'] = this.typeText[e1['activity_goods'][0]['type']];
        }
      });
      this.displayService.getActivityGoodsList(e.id, e['activity_goods'][0]['id']).subscribe(res => {
        if (res.code === 2000) {
          this.activityList[i]['goodsDetail'] = res.data;
        }
      });
    });
    this.isConfirmActivityLoading = false;
    this.activityModalVisible = false;
    // this.checkedActivityInfo.map((e, i) => {
    //   e['flexable'] = false;
    //   this.currentClickActivity.map((e1,i1) => {
    //     if(e == e1) {
    //       e['type'] = this.typeText[e1['activity_goods'][0]['type']];
    //     }
    //   });
    //   this.displayService.getActivityGoodsList(e['id'], e['activity_goods'][0]['id']).subscribe(res => {
    //     if (res.code === 2000) {
    //       this.activityList[i]['goodsDetail'] = res.data;
    //     }
    //   });
    // });
    this.isConfirmActivityLoading = false;
    this.activityModalVisible = false;
    console.log(this.num);
  }

  //获取活动商品列表
  getActivityGoodsList(activityId, activityGoodsId) {
    this.displayService.getActivityGoodsList(activityId, activityGoodsId).subscribe(res => {
      if (res.code === 2000) {
        this.activityList[this.activityClickIndex]['goodsDetail'] = res.data;
      }
    })
  }

  getActivityGoods(activityId, activityGoodsId, index) {
    this.displayService.getActivityGoodsList(activityId, activityGoodsId).subscribe(res => {
      if (res.code === 2000) {
        this.activityList[index]['goodsDetail'] = res.data;
      }
    })
  }

  //查看活动商品
  toggleFlexable(i) {
    this.activityClickIndex = i;
    let target = this.activityList[i];
    target['flexable'] = !target['flexable'];
    if (target['flexable']) {
      let activityId = target['id'], activity_goods_id = target['activity_goods'][0]['id'];
      this.getActivityGoodsList(activityId, activity_goods_id);
    }
  }
  //切换checked查看商品
  toggleViewActivityGoods(i) {
    this.checkedActivityInfo[i]['flexable'] = !this.checkedActivityInfo[i]['flexable'];
  }



  dealGoods(e,data) {
    this.goodsList.map((item,i) => {
      if(item.id == data.id) {
        if(this.activity_goods_ids.length == 0) {
          if(e) {
            item['checked'] = true;
            this.activity_goods_ids.push(data);
            this.cacheCurrentIds.push(item.id);
          }
        } else {
          if(e) {
            let num = 0;
            this.activity_goods_ids.map((item1,i) => {
              if(item1.id != data.id && num === 0) {
                item['checked'] = true;
                this.activity_goods_ids.push(data);
                this.cacheCurrentIds.push(item.id);
                // this.checkedGoodsInfo.map((item3) => {
                //   if(item3.id == data.id) {
                //     for(let k in this.recoverGoodsIds) {
                //       if(this.recoverGoodsIds[k]['id']  == data.id) {
                //         this.recoverGoodsIds.splice(parseInt(k),1);
                //       }
                //     };
                //   }
                // })
                num++;
              }
              return;
            });
          } else {
            this.activity_goods_ids.map((item2,i) => {
              if(item2.id == data.id) {
                item['checked'] = false;
                let index = this.cacheCurrentIds.indexOf(item.id);
                this.cacheCurrentIds.splice(index,1);
                // this.checkedGoodsInfo.map((item3) => {
                //   if(item3.id == data.id) {
                //     this.recoverGoodsIds.push(item2);
                //   }
                // });
                this.activity_goods_ids.splice(i,1);
                return;
              }
              return;
            });
          }
        }
      }
    });
    this.currentClickGoods = this.activity_goods_ids;
  }


  goBack(){
    this.router.navigate(['member/activity/list']);
  }
  dealActivity(e,data) {
    this.activityList.map((item,i) => {
      if(item.id == data.id) {
        if(this.activity_ids.length == 0) {
          if(e) {
            item['checked'] = true;
            data['type'] = this.typeText[item['activity_goods'][0]['type']];
            this.activity_ids.push(data);
            this.cacheCurrentActivityIds.push(item.id);
          }
        } else {
          if(e) {
            let num = 0;
            this.activity_ids.map((item1,i) => {
              if(item1.id != data.id && num === 0) {
                item['checked'] = true;
                data['type'] = this.typeText[item['activity_goods'][0]['type']];
                this.activity_ids.push(data);
                this.cacheCurrentActivityIds.push(item.id);
                num++;
              }
              return;
            });
          } else {
            this.activity_ids.map((item2,i2) => {
              if(item2.id == data.id) {
                item['checked'] = false;
                let index = this.cacheCurrentActivityIds.indexOf(item.id);
                this.cacheCurrentActivityIds.splice(index,1);
                this.activity_ids.splice(i2,1);
                return;
              }
              return;
            });
          }
        }
      }
    });
    this.currentClickActivity = this.activity_ids;
  }

  _submitForm() {

    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    this.fileChange();

    if(this.validateForm.valid && !this.picError) {
      this.submitStatus = true;
      this.description = this.editor.clickHandle();
      let goods_ids = [];
      let activity_ids = [];
      if(this.checkedActivityInfo.length) {
        this.checkedActivityInfo.map((e,i) => {
          activity_ids.push(e.id);
        });
      }
      if(this.checkedGoodsInfo.length) {
        this.checkedGoodsInfo.map((e,i) => {
          goods_ids.push(e.id);
        });
      }
      let data = {};
      data['title'] = this.validateForm.controls['title'].value;
      data['id'] = this.validateForm.controls['id'].value;
      data['description'] = this.description;
      data['goods_ids'] = JSON.stringify(goods_ids);
      data['activity_ids'] = JSON.stringify(activity_ids);
      data['applet_uuid'] = this.localStorageService.getNowApplet()['applet_uuid'];
      this.activityService.editActivityPlan(data).subscribe(res => {
        if(res.code === 2000) {
          if(this.ImageChange) {
              this.uploadImg(this.id);
          } else {
              this.submitStatus = false;
              this._message.create('success', '修改成功');
              this.router.navigate(['member/activity/list']);
          }
        } else {
          this._message.create('error',res.message);
          this.submitStatus = false;
        }
      })
    }
  }
}
